#include <stdio.h>
#include <string.h>
#include "mpi.h"

int main(int argc, char *argv[])
{
	int rank, size, next, prev, tag = 123, msg_size = 20;
	char message[msg_size + 1];
    

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

	/* If there is only one process*/
 	if(size == 1) {
		printf("Not enough member to play the game\n");
		MPI_Finalize();
		return 0;
 	}
 	
    /* Calculate the rank of the next process in the ring. */
    next = (rank + 1) % size;
    prev = (rank + size - 1) % size;

	/* The first process sends a message to the next one. */
    if (prev > rank) {
    	fprintf(stderr, "Please input a message(maximum 20 characters): ");
    	fgets(message, msg_size + 1, stdin);
    	if(strlen(message) < msg_size)
    		message[strlen(message) - 1] = '\0';
		MPI_Send(message, strlen(message) + 1, MPI_CHAR, next, tag, MPI_COMM_WORLD);
		printf("Process %d sending the message to Process %d\n", 
               rank, next);
    }
    /* Processes in the middle receive the message from 
    	the	previous one and forward the message to the next one. */
    else if (prev < rank && rank < next) {
        MPI_Recv(&message, msg_size + 1, MPI_CHAR, prev, tag, MPI_COMM_WORLD,
                 MPI_STATUS_IGNORE);
        MPI_Send(message, strlen(message) + 1, MPI_CHAR, next, tag, MPI_COMM_WORLD);
        printf("Process %d forwarding a message to Process %d\n", 
               rank, next);
    }
    /* The last process receives the message and prints it out. */
    else {
    	MPI_Recv(&message, msg_size + 1, MPI_CHAR, prev, tag, MPI_COMM_WORLD,
                 MPI_STATUS_IGNORE);
        printf("Process %d receiving a message: %s\n", rank, message);
	}
    
    MPI_Finalize();
    return 0;
}
